<template>
  <div class="Signing-Power-Attorney-con">

    <a-modal :title="winConfig.title" :visible="winConfig.visible" :width="800" :wrapClassName="'spa-win-con'"
      @cancel="handleCancel" :footer="null">
      <!-- <pdfBox :url="winConfig.pdfUrl"></pdfBox> -->
      <!-- style='border: 1px solid #ccc;height: 600px' -->
      <p-PreviewShow :model="'page'" :event="()=>{}" :url='winConfig.pdfUrl' :isShowWatermark="true" :config="{title:'',visible: false, loading: false, width: '50vw',height: '60vh' }"></p-PreviewShow>
      <div class="footer">
        <a-button class="f-btn" :disabled="btnDisabled" type="primary" @click="modelBtnEvent(1)" icon="twitter">
          下载后邮寄</a-button>
        <a-button class="f-btn" :disabled="btnDisabled" type="primary" @click="modelBtnEvent(2)" icon="edit">
          线上签署</a-button>
      </div>
    </a-modal>
    <a-modal :title="winConfig1.title" :visible="winConfig1.visible" @ok="handleOk1" @cancel="handleCancel1"
      :wrapClassName="'spa-win-con'" :footer="null">
      <a-form-model :model="winConfig1.form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="法人手机号">
          <!-- <a-input v-model="winConfig1.form.phone" /> -->
          <div>{{ winConfig1.form.phone }}</div>
        </a-form-model-item>
        <a-form-model-item label="填写验证码">
          <div style="display: flex; justify-content: center; align-items: center;">
            <a-input v-model="winConfig1.form.verificationCode">
              <a-icon slot="prefix" type="code" style="color:#4266E5" />
            </a-input>
            <!-- icon="code" -->
            <a-button class="f-btn" :disabled="winConfig1.form.vcBtnDisabled" type="primary" @click="modelBtnEvent(3)">
              {{ winConfig1.form.vcBtnLabel }}</a-button>
          </div>
        </a-form-model-item>

      </a-form-model>
      <div class="footer">

        <a-button class="f-btn" type="primary" @click="modelBtnEvent(4)" icon="check"> 确认签约</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import getDataForDB from '@/api/qsbBusinessManagement'
import * as Util from '@/utils/util'

export default {
  name: 'SigningPowerAttorney',
  props: {
    show: { type: Boolean },
    dataList: { type: Array },
    event: { Type: Function }
  },
  // components: { pdfBox },
  data() {
    return {
      btnDisabled: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      winConfig: {
        visible: false,
        title: '委托书签署',
        pdfUrl: '',
        dataList: {}
      },
      winConfig1: {
        visible: false,
        title: '电子签约',
        form: {
          phone: '--',
          verificationCode: '',
          vcBtnDisabled: false,
          vcBtnLabel: '发送验证码',
        }
      },
      resType:0, // 表示关闭操作的类型  0 表示只关闭；  1 表示成功关闭；  2 表示错误关闭
    }
  },
  watch: {
    show: {
      handler(val) {
        if (this.isType.isBoolean(val) && val === true) {
          this.resType = 0
          this.SigningPowerAttorney1(val)
        }
      },
      deep: true,
      // immediate: true
    },
  },
  methods: {
    countDownFun() {
      let seconds = 120;// 30
      const oldLabel = '发送验证码'
      this.winConfig1.form.vcBtnDisabled = true
      this.winConfig1.form.vcBtnLabel = `(${seconds})${oldLabel}`
      let promise = new Promise((resolve, reject) => {
        // console.log('************************启动定时器************************');
        this.setTimer = setInterval(() => {
          seconds -= 1;
          this.winConfig1.form.vcBtnLabel = `(${seconds})${oldLabel}`
          // console.log(`************************启运行定时器 ${seconds}************************`);
          if (seconds <= 0) {
            this.winConfig1.form.vcBtnLabel = oldLabel
            resolve(this.setTimer)
          }
        }, 1000)
      })
      promise.then((setTimer) => {
        // console.log('************************清理定时器************************');
        clearInterval(setTimer);
        this.winConfig1.form.vcBtnDisabled = false
      })

    },
    modelBtnEvent(type) {
      if (type == 1) {
        // 下载后邮寄
        const self = this
        const h = this.$createElement;
        this.$info({
          title: '邮寄地址',
          content: h('div', {}, [
            h('p', '地址：湖北省荆州市沙市区义乌小商品城二期2栋4楼中雄公司'),
            h('p', '收件人：孟瑞华'),
            h('p', '电话：18271007211'),
          ]),
          okText: '复制邮寄信息',
          onOk() {
            Util.copyLinkContent("地址：湖北省荆州市沙市区义乌小商品城二期2栋4楼中雄公司   收件人：孟瑞华  电话：18271007211", self)
          },
        });
        this.uploads()
      }
      if (type == 2) {
        // 线上签署
        this.winConfig1.visible = true
      }
      if (type == 3) {
        // 发送验证码
        // this.winConfig1.visible = true
        getDataForDB('发送签署委托书验证码')
        this.countDownFun()
      }
      if (type == 4) {
        // 确认签约
        const param = { agreeId: this.winConfig.dataList.agreeId, code: this.winConfig1.form.verificationCode }
        getDataForDB('渠道签署委托书', param).then(res => {
          const { success, message } = res
          if (success) {
            this.resType = 1
            this.$message.success('签约成功')
          } else {
            this.resType = 2
            this.$message.warning(message || '签约失败')
          }
          this.winConfig1.visible = false
        })

      }

    },
    // 签署委托书
    SigningPowerAttorney1(visible) {
      this.SigningPowerAttorney(visible)
      // this.winConfig.pdfUrl = 'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/contract/2023-02/16765299811842.委托代征协议（个体、个独注册）.pdf'
      // this.$nextTick(() => {
      //   PDFObject.embed(this.winConfig.pdfUrl, "#pdfBox");
      // })
      // this.winConfig.visible = visible
    },
    //下载
    uploads() {
      let url = this.winConfig.pdfUrl;
      //从链接上截取文件名
      let fileName = Util.getCaptionFileName(url);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.setAttribute('target', '_blank');
      fileName && a.setAttribute('download', fileName);
      a.href = url;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    handleOk() {
      this.winConfig.visible = false
    },
    handleOk1() {
      this.winConfig1.visible = false
    },
    handleCancel() {
      this.winConfig.visible = false
      this.event && this.event(this.resType)
    },
    handleCancel1() {
      this.winConfig1.visible = false
    },
    /**
     * 生成要签署的委托书
     * @param {*} visible
     */
    SigningPowerAttorney(visible) {
      const param = []
      this.dataList.forEach(item => {
        param.push({
          "certNo": item.cardNumber,
          "entId": item.id,
          "entLegalName": item.legalName
        })
      })
      getDataForDB('web端生成委托书', param).then(res => {
        const { success, result, message } = res
        if (success) {
          this.winConfig.pdfUrl = result.contractUrl
          this.winConfig1.form.phone = result.legalPhone
          this.winConfig.dataList = result
          this.$nextTick(() => {
            PDFObject.embed(this.winConfig.pdfUrl, "#pdfBox");
          })
          this.btnDisabled = false
        } else {
          this.btnDisabled = true
          this.$message.warning(message || '获取委托书信息失败')
        }
        this.winConfig.visible = visible
      })
    },
  }
}
</script>

<style lang="less">
.Signing-Power-Attorney-con {}

.spa-win-con {
  .ant-modal-content {
    .ant-modal-body {
      .footer {
        height: 50px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .f-btn {
          margin: 0 5px;
        }
      }
    }
  }
}</style>
